import express from 'express';
import { Request, Response } from "express";
import { AppDataSource } from "../config/database";
import { success, failure } from '../utils/responses';
import { AuthRequest } from "../middlewares/user-auth";
import { BadRequest, NotFound } from "http-errors";
import { Article } from "../entities/Article";
import { Post } from "../entities/Post";
import { Comment } from "../entities/Comment";
import { Like, LikeType } from "../entities/Like";
import { Repository } from "typeorm";

const router = express.Router()

/**
 * 查询当前用户是否点赞
 */
router.get('/', async function (req: Request, res: Response) {
  try {
    // 获取type和targetId
    const query = req.query
    const type = Number(query.type)
    const targetId = Number(query.targetId)
    if (isNaN(targetId)) throw new BadRequest("请传入正确的id")
    if (!(type && type in LikeType)) throw new BadRequest('请传入合法的类型')

    // 在点赞表中查找当前登录用户有没有为targetId点赞
    const userId = (req as AuthRequest).id

    const likeRepository = AppDataSource.getRepository(Like)
    const isLike = await likeRepository.exists({
      where: {
        userId,
        type,
        targetId
      }
    })

    success(res, '成功查询点赞状态', { isLike })
  } catch (error) {
    failure(res, error)
  }
});

/**
 * 点赞、取消赞
 */
router.post('/', async function (req: Request, res: Response) {
  try {
    // 获取type和targetId
    const { type, targetId } = req.body

    if (isNaN(targetId)) throw new BadRequest("请传入正确的id")
    if (!(type && type in LikeType)) throw new BadRequest('请传入合法的类型')

    // 检查type下有没有targetId的文章（或帖子、评论）
    let repository: Repository<Article | Post | Comment>
    let targetObject: Article | Post | Comment | null = null
    if (type === LikeType.ARTICLE) {
      repository = AppDataSource.getRepository(Article) as Repository<Article>
      targetObject = await repository.findOneBy({ id: targetId }) as Article
      if (!targetObject) throw new NotFound('没有找到文章')
    } else if (type === LikeType.POST) {
      repository = AppDataSource.getRepository(Post) as Repository<Post>
      targetObject = await repository.findOneBy({ id: targetId }) as Post
      if (!targetObject) throw new NotFound('没有找到帖子')
    } else if (type === LikeType.COMMENT) {
      repository = AppDataSource.getRepository(Comment) as Repository<Comment>
      targetObject = await repository.findOneBy({ id: targetId }) as Comment
      if (!targetObject) throw new NotFound('没有找到评论')
    }

    // 在点赞表中查找当前登录用户有没有为targetId点赞
    const userId = (req as AuthRequest).id

    const likeRepository = AppDataSource.getRepository(Like)
    const like = await likeRepository.findOne({
      where: {
        userId,
        type,
        targetId
      }
    })

    if (like) {
      // 找到点赞了，应该取消赞
      await likeRepository.remove(like)

      targetObject!.likeCount--
      await repository.save(targetObject)

      success(res, '取消赞成功')
    } else {
      // 还没有点赞，应该点赞
      const newLike = new Like()
      newLike.type = type
      newLike.userId = userId
      newLike.targetId = targetId
      await likeRepository.save(newLike)

      targetObject!.likeCount++
      await repository.save(targetObject)

      success(res, '点赞成功')
    }
  } catch (error) {
    failure(res, error)
  }
});

export default router
